package com.sdkj.fixed.asset.assets.controller;

import com.alibaba.fastjson.JSONObject;
import com.sdkj.fixed.asset.api.assets.WarehouseApi;
import com.sdkj.fixed.asset.api.assets.in_vo.WarehousePagesParam;
import com.sdkj.fixed.asset.api.assets.in_vo.WarehouseParam;
import com.sdkj.fixed.asset.api.assets.out_vo.AssetSupplierResult;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseLogResult;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseResult;
import com.sdkj.fixed.asset.assets.service.AssetLogService;
import com.sdkj.fixed.asset.assets.service.AssetSupplierService;
import com.sdkj.fixed.asset.assets.service.WarehouseService;
import com.sdkj.fixed.asset.assets.util.CacheUtils;
import com.sdkj.fixed.asset.assets.util.ExcelUtils;
import com.sdkj.fixed.asset.assets.util.FileManager;
import com.sdkj.fixed.asset.common.base.BaseResultVo;
import com.sdkj.fixed.asset.common.base.PageBean;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.AssetLog;
import com.sdkj.fixed.asset.pojo.assets.Warehouse;
import com.sun.javafx.binding.StringFormatter;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author zhangjinfei
 * @Description //TODO 资产入库控制
 * @Date 2020/7/21 13:32
 */
@RestController
public class WarehouseController implements WarehouseApi {

    private Logger log  = LoggerFactory.getLogger(WarehouseController.class);
    @Autowired
    private AssetSupplierService assetSupplierService;
    @Autowired
    private AssetLogService logService;
    @Autowired
    private WarehouseService service;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheUtils cacheUtils;

    /**
     * 分页查询资产
     * @param params
     * @return
     */
    @Override
    public BaseResultVo<WarehouseResult> queryPages(PageParams<WarehousePagesParam> params) {
        List<WarehouseResult> warehouses = service.queryPages(params);
        if (warehouses==null){
            warehouses = new ArrayList<>();
        }
        PageBean<WarehouseResult> pageBean = new PageBean<WarehouseResult>(warehouses);
        return BaseResultVo.success(pageBean);
    }

    /**
     * 通过查询资产
     *
     * @param areaId
     * @return
     */
    @Override
    public BaseResultVo<Warehouse> queryByClassIdAndAreaId(String classId,String areaId) {
        List<Warehouse> warehouseList = service.queryByClassIdAndAreaId(classId,areaId);
        return  BaseResultVo.success(warehouseList);
    }

    /**
     * 选择资产分页查询资产
     *
     * @param params
     * @return
     */
    @Override
    public BaseResultVo<WarehouseResult> queryStatePages(PageParams<WarehousePagesParam> params) {
        List<WarehouseResult> warehouses = service.queryStatePages(params);
        PageBean<WarehouseResult> pageBean = new PageBean<WarehouseResult>(warehouses);
        return BaseResultVo.success(pageBean);
    }

    public BaseResultVo<WarehouseResult> queryWithdrawal(@RequestBody WarehousePagesParam param) {
        if(param.getUserId()==null || param.getUserId().equals("")){
            throw new LogicException("用户信息有误");
        }
        param.setState("1");
        List<WarehouseResult> warehouses = service.queryWithdrawal(param);
        return BaseResultVo.success(warehouses);
    }
    /**
     * 查询资产
     * @param assetId
     * @return
     */
    @Override
    public BaseResultVo<WarehouseResult> queryByAssetId(String assetId) {
        WarehouseResult warehouse = service.queryByAssetId(assetId);
        return BaseResultVo.success(warehouse);
    }

    /**
     * 员工的条数查询
     * @param userId
     * @return
     */
    @Override
    public BaseResultVo<Integer> queryCountByUserId(String userId) {
        if(userId==null || userId.equals("")){
            throw new LogicException("用户信息有误");
        }
        Integer i = service.queryCountByUserId(userId);
        return BaseResultVo.success(i);
    }

    /**
     * 所属公司查询资产
     *
     * @param companyId
     * @return
     */
    @Override
    public BaseResultVo<WarehouseResult> queryByCompanyId(String companyId) {
        List<WarehouseResult> warehouses = service.queryByCompanyId(companyId);
        return BaseResultVo.success(warehouses);
    }

    /**
     * 员工的查询资产 App
     *
     * @param userId
     * @return
     */
    @Override
    public BaseResultVo<WarehouseResult> queryByUserId(String userId,String searchName) {
        if(userId==null || userId.equals("")){
            throw new LogicException("用户信息有误");
        }
        List<WarehouseResult> warehouseList = service.queryByUserId(userId,searchName);
        return BaseResultVo.success(warehouseList);
    }

    /**
     * 分类查询资产 App
     *
     * @param classId
     * @return
     */
    @Override
    public BaseResultVo<WarehouseResult> queryByClassId(String classId,String searchName) {
        List<WarehouseResult> warehouseList = service.queryByClassId(classId,searchName);
        return BaseResultVo.success(warehouseList);
    }

    /**
     * 处理记录
     * @param assetId
     * @return
     */
    @Override
    public BaseResultVo<WarehouseResult> queryLogByAssetId(String assetId) {
        List<AssetLog> assetLogList = logService.queryLogByAssetId(assetId);
        return BaseResultVo.success(assetLogList);
    }

    /**
     * 维保信息
     * @param assetId
     * @return
     */
    @Override
    public BaseResultVo<AssetSupplierResult> queryMaintainByAssetId(String assetId) {
        AssetSupplierResult result = assetSupplierService.queryMaintainByAssetId(assetId);
        return BaseResultVo.success(result);
    }

    /**
     * 添加资产
     * @param warehouse
     * @return
     */
    @Override
    public BaseResultVo<WarehouseParam> insertWarehouse(WarehouseParam warehouse) {
        log.info("入参："+ JSONObject.toJSONString(warehouse));
        Integer i = service.insertWarehouse(warehouse);
        if(i<= 0){
            return BaseResultVo.failure("资产入库添加失败");
        }
        log.info("出参："+JSONObject.toJSONString(warehouse));
        return BaseResultVo.success(warehouse);
    }

    /**
     * 修改资产
     *
     * @param warehouse
     * @return
     */
    @Override
    public BaseResultVo<WarehouseParam> updateWarehouse(WarehouseParam warehouse) {
        log.info("入参："+ JSONObject.toJSONString(warehouse));
        WarehouseResult warehouseResult = service.queryByAssetId(warehouse.getAssetId());
        if(warehouseResult.getLogList()!=null && warehouseResult.getLogList().size()!=0){
            return BaseResultVo.failure("该资产已有处理记录，请使用实物信息变更功能修改资产信息");
        }
        Integer i  = service.updateWarehouse(warehouse);
        if(i<= 0){
            return BaseResultVo.failure("资产入库修改失败");
        }
        log.info("出参："+JSONObject.toJSONString(warehouse));
        return BaseResultVo.success(warehouse);
    }

    /**
     * 删除资产
     *
     * @param assetId
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo<Warehouse> deleteWarehouse(String assetId) throws Exception {
        if(assetId==null){
            return BaseResultVo.failure("资产信息不存在");
        }
        WarehouseResult wh = service.queryByAssetId(assetId);
        if(wh==null){
            return BaseResultVo.failure("资产信息不存在");
        }
        if(wh.getLogList()!=null && wh.getLogList().size()>0 ){
            return BaseResultVo.failure("该资产已有处理记录,删除失败");
        }
        WarehouseParam param  = new WarehouseParam();
        param.setAssetId(wh.getAssetId());
        // 标记删除
        param.setIsDelete(1);
        Integer i = service.updateWarehouse(param);
        if(i<= 0){
            return BaseResultVo.failure("该资产删除失败");
        }
        return BaseResultVo.success(wh);
    }

    /**
     * 导入模板下载
     *
     * @param response
     * @throws Exception
     */
    @Override
    public void importTemplate(HttpServletResponse response) throws Exception {
        String filePath = FileManager.getReportPath("template","资产导入模板.xls");
        File file = new File(filePath);
        String fileName = "资产导入模板.xls";
        Workbook wb=service.importTemplate(file);
        response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"iso8859-1"));
        response.setContentType("application/ms-excel;charset=UTF-8");
        OutputStream out=response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();
    }

    /**
     * 批量导入资产
     *
     * @param file
     * @throws Exception
     */
    @Override
    public BaseResultVo importAssetData(MultipartFile file) throws Exception {
        String name=file.getOriginalFilename();
        if(file == null){
            throw  new LogicException("文件不能为空");
        }
        if(!name.endsWith(".xls")){
            throw  new LogicException("文件类型必须为【.xls】");
        }
        if(file.getSize() > 10*1024*1024){
            throw  new LogicException("文件最大允许10MB");
        }
        Boolean flag = null;
        flag = service.importAssetData(file);
        if(flag){
            return BaseResultVo.success("上传文件数据成功");
        }
//        ------------------------------
        return BaseResultVo.failure("上传文件数据有误");
    }

    /**
     * 导出资产
     * @throws Exception
     */
    @Override
    public void exportWarehouse(HttpServletResponse response,String token,String companyDeptId ,String searchName) throws Exception {
        String fileName = "资产列表"+ TimeTool.getTimeDate14();
        List<WarehouseResult> list = service.queryAll(token,companyDeptId,searchName);
        ExcelUtils.exportExcel(list,WarehouseResult.class,fileName,response);
    }

    public void exportWarehouseResume(HttpServletResponse response,String token,String companyDeptId ,String searchName) throws Exception{
        List<WarehouseResult> list = service.queryAll(token,companyDeptId,searchName);
        String orgId = cacheUtils.getUserCompanyId(token);

//        Example exampleCount  =  new Example(Warehouse.class);
//        Example.Criteria criteriaCount = exampleCount.createCriteria();
//        criteriaCount.andEqualTo("isDelete","0");
//        criteriaCount.andEqualTo("orgId", orgId);
//        int count = service.selectCountByExample(exampleCount);
//
//        Example example =  new Example(Warehouse.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("isDelete","0");
//        criteria.andEqualTo("state","在用");
//        criteria.andEqualTo("orgId",orgId);
//        int delCount = service.selectCountByExample(example);

        List<WarehouseLogResult> resultList = new ArrayList<>();

        // 在用资产数量
        AtomicInteger count = new AtomicInteger(0);
        BigDecimal totalAmount=new BigDecimal("0");
        // list 集合不能为null
        if(list!=null){
            list.stream().forEach(e->{
                WarehouseLogResult wlr = new WarehouseLogResult();
                BeanUtils.copyProperties(e,wlr);
                resultList.add(wlr);
                if(StringUtils.isEmpty(e.getAmount())){
                    e.setAmount("0");
                }
                if (StringUtils.equals("在用",e.getState())){
                    count.getAndIncrement();
                }
            });
            for(WarehouseResult w:list) {
                totalAmount = totalAmount.add(new BigDecimal(w.getAmount()));
            };
        }else{
            list = new ArrayList<>();
        }
        String fileName = "资产履历"+ TimeTool.getTimeDate14();
        String title = "资产履历";
        String sheetName=fileName;
        String secondTitle =" 资产总数：[ %s ] 资产总额：[ %s ] 正常在用资产：[ %s ] ";
        secondTitle = StringFormatter.format(secondTitle, list.size(), totalAmount, count.get()).getValue();
        ExcelUtils.exportExcel(resultList,title,secondTitle,sheetName,WarehouseLogResult.class,fileName,response);
    }

    public void printCard(HttpServletResponse response, String assetIds) throws Exception{
        List<String> assetIdList = Arrays.asList(assetIds.split(","));
        String fileName = "资产卡片"+ TimeTool.getTimeDate14();
        Workbook workbook=service.printCard(assetIdList);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
        workbook.write(response.getOutputStream());
    }

    @Override
    public void printWarehousing(HttpServletResponse response, String assetIds) throws Exception {
        List<String> assetIdList = Arrays.asList(assetIds.split(","));
        String fileName = "资产入库单"+ TimeTool.getTimeDate14();
        Workbook workbook=service.printWarehousing(assetIdList);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
        workbook.write(response.getOutputStream());
    }
}
